package utils;

import io.jsonwebtoken.*;
import java.util.Date;

public class JwtUtils {
    // 密钥，生产环境应存储在安全位置,不能有件号
    private static final String SECRET_KEY = "zvbaY/uFE40WsI7alCTyPQ/zj7EojH8ZiqH8nK2J8Bw=";
    // Token有效期（2小时）
    private static final long EXPIRATION_TIME = 6 * 60 * 60 * 1000;

    public static String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static Claims validateToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (SignatureException | MalformedJwtException | ExpiredJwtException |
                 UnsupportedJwtException | IllegalArgumentException e) {
            throw new RuntimeException("Invalid JWT Token", e);
        }
    }
    
    public static String getUsernameFromToken(String token) {
        return validateToken(token).getSubject();
    }

}
